package com.j1cn.medical.manage.webservice.config;

import com.j1cn.medical.manage.biz.UserService;
import com.j1cn.medical.manage.dao.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.security.PermissionCollection;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @author ernest
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<SysUser> sysUser = userService.getByUserName(username);
       return sysUser.map(sys ->{
            SimpleGrantedAuthority authority1 = new SimpleGrantedAuthority("list");
            SimpleGrantedAuthority authority2 = new SimpleGrantedAuthority("query");
            List<GrantedAuthority> authority = Arrays.asList(authority1,authority2 );
            var user = new User(sys.getUserName(),sys.getPassword(), authority);
            return user;
        } ).orElseGet(null);
    }
}
